package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.live.activity.R;
import com.live.adapter.LiveSearchSimpleAdapter;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveSearch extends AsyncTask<String, Integer, String> {

	private Context context = null;

	private LiveSearchSimpleAdapter adapter = null;
	private List<Map<String, Object>> liveMatchList = null;
	private View liveSearchFoot = null;
	private int total = 0;

	private String locale = LiveTools.getLocaleLanguage();

	private boolean more = false;

	public LiveSearch(Context context, LiveSearchSimpleAdapter adapter, List<Map<String, Object>> liveMatchList,
			View liveSearchFoot, boolean more) {
		this.context = context;
		this.adapter = adapter;
		this.liveMatchList = liveMatchList;
		this.liveSearchFoot = liveSearchFoot;
		this.more = more;
	}

	ProgressDialog mProgressDialog = null;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
		if (!more) {
			this.mProgressDialog = new ProgressDialog(context);
			this.mProgressDialog.setMessage(Constant.LOAD_DATA);
			this.mProgressDialog.show();
		}
	}

	@Override
	protected String doInBackground(String... params) {

		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());
		liveMatchList.addAll(getServerData(params[0]));
		publishProgress(new Integer[0]);
		return null;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());
		adapter.notifyDataSetChanged();

	}

	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		if (!more) {
			this.mProgressDialog.dismiss();
		}
		TextView loadMore = (TextView) liveSearchFoot.findViewById(R.id.load_more);
		ProgressBar progressBar = (ProgressBar) liveSearchFoot.findViewById(R.id.load_more_prog_bar);

		if (liveMatchList.size() == total) {
			if (total == 0) {
				loadMore.setVisibility(View.VISIBLE);
				loadMore.setText(R.string.load_btn_result);
			} else {
				loadMore.setVisibility(View.GONE);
			}
		} else {
			loadMore.setVisibility(View.VISIBLE);
			loadMore.setText(R.string.load_btn_more);
			loadMore.setText(loadMore.getText() + "(" + liveMatchList.size() + "/" + total + ")");
		}
		progressBar.setVisibility(View.GONE);
	}

	public List<Map<String, Object>> getServerData(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							total = Integer.parseInt(new JSONObject(out).getString("total"));
							JSONArray matches = new JSONObject(out).getJSONArray("results");
							for (int i = 0; i < matches.length(); i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								String matchTime = (String) matches.getJSONObject(i).get("matchTime");
								map.put("matchId", matches.getJSONObject(i).get("matchId"));
								map.put("matchOptaId", matches.getJSONObject(i).get("matchOptaId"));
								map.put("matchName", LiveTools.tradToSimp(matches.getJSONObject(i).get("matchName")
										.toString(), locale));
								map.put("matchCategory", matches.getJSONObject(i).get("matchCategory"));
								map.put("matchTime", matchTime.substring(2, 10) + "\n" + matchTime.substring(11, 16));
								map.put("matchTimeAll", matchTime);
								map.put("homeTeam",
										LiveTools.tradToSimp(matches.getJSONObject(i).get("homeTeam").toString()
												.replace("?", "·"), locale));
								map.put("homeTeamName", matches.getJSONObject(i).get("homeTeamName").toString()
										.replace("?", "·"));
								map.put("homeTeamScore", matches.getJSONObject(i).get("homeTeamScore"));
								map.put("homeTeamPic", matches.getJSONObject(i).get("homeTeamPic"));
								map.put("visitTeam",
										LiveTools.tradToSimp(matches.getJSONObject(i).get("visitTeam").toString()
												.replace("?", "·"), locale));
								map.put("visitTeamName", matches.getJSONObject(i).get("visitTeamName").toString()
										.replace("?", "·"));
								map.put("visitTeamScore", matches.getJSONObject(i).get("visitTeamScore"));
								map.put("visitTeamPic", matches.getJSONObject(i).get("visitTeamPic"));
								if ("实录".equals(matches.getJSONObject(i).get("matchRecord").toString())
										|| "直播间".equals(matches.getJSONObject(i).get("matchRecord").toString())) {
									map.put("matchStatus", matches.getJSONObject(i).get("matchStatus"));
									map.put("matchRecord", "●");
								} else {
									if (Constant.MATCH_STATUS_3.equals(matches.getJSONObject(i).get("matchStatus")
											.toString())) {
										map.put("matchStatus", Constant.MATCH_STATUS_2);
									} else {
										map.put("matchStatus", matches.getJSONObject(i).get("matchStatus"));
									}
									map.put("matchRecord", null);
								}
								map.put("matchStatus", LiveTools.tradToSimp(map.get("matchStatus").toString(), locale));
								map.put("matchWatch", matches.getJSONObject(i).get("matchWatch"));
								data.add(map);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			Toast.makeText(context, "远程服务器无响应，请稍候再试！", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return data;
	}
}